package com.starblink.imgsearch.result.ui

import android.graphics.RectF
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.apollographql.apollo3.api.ApolloResponse
import com.starblink.android.basic.BuildConfig
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.ext.string
import com.starblink.android.basic.ext.toast
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.basic.apollo.ext.optional
import com.starblink.android.basic.sensorsdata.helper.ImgIdentifyTrackHelper
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.basic.util.log.YYLogUtils
import com.starblink.imgsearch.camera.OssUploader
import com.starblink.imgsearch.result.data.ImgClipModel
import com.starblink.imgsearch.result.data.ResultBrandModel
import com.starblink.imgsearch.result.data.ResultPriceModel
import com.starblink.rocketreserver.FetchImgSearchAuthTokenQuery
import com.starblink.rocketreserver.ImageIdentify4picV2Query
import com.starblink.rocketreserver.ImageIdentify4postPicQuery
import com.starblink.rocketreserver.ImageIdentifyByAiQuery
import com.starblink.rocketreserver.fragment.PicSearchResultF
import com.starblink.rocketreserver.fragment.PostPicAiInfoF
import com.starblink.rocketreserver.fragment.SearchWordVOF
import com.starblink.rocketreserver.type.PicSearchQuery
import kotlinx.coroutines.launch
import java.io.File

class ResultVM : BaseViewModel() {


    var filePath: String = ""
    var imgUrl: String = ""
    var postPicId: String = ""

    val postAIList = arrayListOf<PostPicAiInfoF>()

    val dataLD = MutableLiveData<PicSearchResultF?>()

    val imgClipData = arrayListOf<ImgClipModel>()

    val boxesList = arrayListOf<String>()

    //识图返回结果顶部品牌
    val brandList = arrayListOf<ResultBrandModel>()
    val priceMapList = hashMapOf<Int, ResultPriceModel>()
    val searchWordMapList = hashMapOf<Int, List<PicSearchResultF.SearchWordList?>?>()

    val brandMapList = hashMapOf<Int, ArrayList<ResultBrandModel>>()

    var curBox: String? = null

    var dataLoaded = false

    val rectBoxes = arrayListOf<RectF>()

    var isLastBoxFromDrag = false

    private val trackHelper by lazyOnNone {
        ImgIdentifyTrackHelper()
    }

    fun loadData() {
        searchWordMapList[0] = null
        this.viewModelScope.launch {
            val success =
                if (imgUrl.isNotEmpty()) {
                    true
                } else {
                    val response: ApolloResponse<FetchImgSearchAuthTokenQuery.Data>? =
                        SkGqlClient.skQuery(query = FetchImgSearchAuthTokenQuery())
                    val ossKeyData: FetchImgSearchAuthTokenQuery.FetchImgSearchAuthToken? =
                        response?.data?.fetchImgSearchAuthToken

                    if (ossKeyData == null) {
//                        toast(string(com.starblink.basic.style.R.string.server_error))
                        YYLogUtils.e("---------------->  ${string(com.starblink.basic.style.R.string.server_error)}")
                        return@launch
                    }
                    imgUrl = ossKeyData.picUrl
                    val file = File(filePath)
                    trackHelper.beginUpload()
                    OssUploader.upload(file, ossKeyData)
                }
            if (filePath.isNotEmpty()) {
                trackHelper.endUpload(File(filePath))
            }

            if (success) {
                if (BuildConfig.DEBUG) {
                    toast("upload success")
                }
                trackHelper.beginIdentify()
                if (postPicId.isNotEmpty()) {
                    val ais = SkGqlClient.skQuery(
                        ImageIdentifyByAiQuery(
                            postPicId = postPicId,
                        )
                    )?.data?.imageIdentifyByAi?.map { it.postPicAiInfoF }?.apply {
                        postAIList.addAll(this)
                        boxesList.addAll(map {
                            it.aiInfo
                        })
                        curBox = boxesList.takeIf { it.isNotEmpty() }?.get(0)
                    }
                    if (ais?.isNotEmpty() == true) {
                        val response2: ApolloResponse<ImageIdentify4postPicQuery.Data>? =
                            SkGqlClient.skQuery(
                                query = ImageIdentify4postPicQuery(
                                    params = PicSearchQuery(
                                        postPicAiInfoId = ais[0].id.optional(),
                                        pageNo = 1.optional(),
                                        pageSize = 10.optional(),
                                        saleableCountryFlag = true.optional(),
                                    )
                                )
                            )

                        response2?.data?.imageIdentify4postPic?.picSearchResultF.let {
                            dataLD.postValue(it)
                            searchWordMapList[0] = it?.searchWordList
                        }

                    } else {
                        dataLD.postValue(null)
                        searchWordMapList[0] = null
                    }
                    dataLoaded = true
                    FlowBus.with<Int>(FlowConst.IMG_SEARCH_OOPS).post(0)
                } else {
                    val response2: ApolloResponse<ImageIdentify4picV2Query.Data>? =
                        SkGqlClient.skQuery(
                            query = ImageIdentify4picV2Query(
                                search = PicSearchQuery(
                                    picUrl = imgUrl.optional(),
                                    pageNo = 1.optional(),
                                    pageSize = 20.optional(),
                                    saleableCountryFlag = true.optional(),
                                )
                            )
                        )
                    response2?.data?.imageIdentify4picV2.let { it ->
                        //successLD.postValue(true)
                        it?.picSearchResultF?.boxes?.takeIf { it.isNotEmpty() }?.mapNotNull {
                            it
                        }?.apply {
                            boxesList.addAll(this)
                        }
                        curBox = it?.picSearchResultF?.currentBoxes

                        dataLD.postValue(it?.picSearchResultF)
                        searchWordMapList[0] = it?.picSearchResultF?.searchWordList
                    }
                    dataLoaded = true
                }
                trackHelper.endIdentify()
            } else {
                if (BuildConfig.DEBUG) {
                    toast("upload error")
                }
            }
        }
    }


}